package net.huashitong.commCtrl;

import com.alibaba.fastjson.JSONArray;
import com.sirdc.modules.core.config.Global;
import com.sirdc.modules.core.web.JsonBaseController;
import com.sirdc.modules.core.web.model.Message;
import com.sirdc.modules.sys.entity.SysFile;
import com.sirdc.modules.sys.service.SysFileService;
import com.sirdc.modules.utils.StringUtils;
import net.huashitong.Indicators.entity.IndicatorBreakdown;
import net.huashitong.Indicators.service.ImportDataService;
import net.huashitong.Indicators.service.IndicatorBreakdownService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.util.UriUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 公用类。
 * 工用的上传 下载，
 */

@Controller
@RequestMapping("/communal")
public class CommCtrl extends JsonBaseController {

    static final String path = "D:/data/gisData/";

    @Autowired
    private SysFileService fileservice;
    @Autowired
    private ImportDataService importDataService;
    @Autowired
    private IndicatorBreakdownService indicatorBreakdownService;

    @Override
    protected String getView(String s) {
        return null;
    }

    //文件上传
    @ResponseBody
    @RequestMapping("/uploadBatch")
    public String uplaodfile(@RequestParam MultipartFile files) {
        String str = null;
        Message msg = new Message();
        if (files == null) {
            msg.setCode("500");
            return null;
        }
        //System.out.println(projectStage);
        Map<String, Object> map = new HashMap<String, Object>();

        try {
            SysFile sysfile = new SysFile();
            fileservice.saveFile(sysfile, files);
            map.put("sysId", sysfile.getSysId());
            msg.setCode("200");
            msg.setData(map);
            str = JSONArray.toJSONString(msg);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return str;
    }

    //文件下载
    @RequestMapping(value = "/download/{id}")
    public void downLoad(@PathVariable String id, HttpServletRequest req, HttpServletResponse resp) throws Exception {
        downLoadFileId(id, req, resp);
    }


    public void downLoadFileId(String fileId, HttpServletRequest req, HttpServletResponse resp) throws Exception {
        SysFile sysFile = fileservice.getById(fileId);
        if (sysFile == null) {
            throw new Exception(" current request path is empty");
        }
        String filepath = sysFile.getUrl();
        int index = filepath.lastIndexOf(Global.USER_DIR);
        if (index >= 0) {
            filepath = filepath.substring(index + Global.USER_DIR.length());
        }
        try {
            filepath = UriUtils.decode(filepath, "UTF-8");
        } catch (Exception e1) {
            // TODO Auto-generated catch block
            logger.error(String.format("解释文件路径失败，URL地址为%s", filepath), e1);
        }
        File file = new File(Global.getUploadBaseDir() + filepath);
        resp.reset();
        InputStream inputStream = new FileInputStream(file);
        try {
            String fileName = sysFile.getFilename();
            String n = new String(fileName.getBytes(), "iso8859-1");
            resp.setHeader("Content-Type", "application/x-download");
            resp.setHeader("Content-Disposition", "attachment; filename=" + n + "." + sysFile.getFileType());
            FileCopyUtils.copy(inputStream, resp.getOutputStream());
            return;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            throw new FileNotFoundException("请求的文件不存在");
        }
    }


    /**
     * 导入指标数据
     * @param file
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/importIndicatorBreakdown")
    public Message importData(@RequestParam(value = "file") MultipartFile file) {
        if (file.getOriginalFilename().endsWith(".xlsx") == false) {
            return coverMessage("500", "文件后缀不对");
        }
        String filePath;
        try {
            write(file.getOriginalFilename(), file.getInputStream());
            filePath = path + file.getOriginalFilename();
            filePath = new String(filePath.getBytes("utf-8"), "utf-8");
            if (StringUtils.isBlank(filePath)) {
                return coverMessage("500", "filePath为空");
            }

            List<IndicatorBreakdown> list = importDataService.importIndicators(filePath);
            indicatorBreakdownService.batchSave(list);

            return coverMessage("200", "导入成功！");
        } catch (Exception e) {
            return coverMessage("500", "导入失败！", e.getMessage());
        }
    }

    private static void write(String filename, InputStream in) {
        File file = new File(path);
        if (!file.exists()) {
            if (!file.mkdirs()) {// 若创建文件夹不成功
                System.out.println("Unable to create external cache directory");
            }
        }
        File targetfile = new File(path + filename);
        OutputStream os = null;
        try {
            os = new FileOutputStream(targetfile);
            int ch = 0;
            while ((ch = in.read()) != -1) {
                os.write(ch);
            }
            os.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                os.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 查询库内的数据时间
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/queryIndicatorAllDateTimes")
    public List<String> queryAllDateTimes(){
        return indicatorBreakdownService.queryAllDateTimes();
    }

}
